package com.andy.dao.impl;

import com.andy.dao.TransferDao;
import com.andy.dao.entity.TAccount;
import com.andy.infrastructure.ioc.annotation.Autowire;
import com.andy.infrastructure.ioc.annotation.Repository;
import com.andy.infrastructure.util.CurrentThreadConnectionManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Repository
public class TransferDaoImpl implements TransferDao {

    @Autowire
    private CurrentThreadConnectionManager currentThreadConnectionManager;

    /**
     * 卡号查询账户对象
     *
     * @param cardNo
     * @return
     * @throws Exception
     */
    @Override
    public TAccount queryAccountByCardNo(String cardNo) throws Exception {
        Connection conn = currentThreadConnectionManager.getCurrentThreadConn();

        String sql = " SELECT * FROM T_ACCOUNT WHERE CARD_NO=? ";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1,cardNo);
        ResultSet rs = preparedStatement.executeQuery();

        TAccount account = new TAccount();
        while(rs.next()){
            account.setId(rs.getInt("ID"));
            account.setCardNo(rs.getString("CARD_NO"));
            account.setBalanceAmount(rs.getDouble("BALANCE_AMOUNT"));
        }

        return account;
    }

    /**
     * 修改单个账户余额
     * @param account
     * @throws Exception
     */
    @Override
    public int updateCustBalanceAmount(TAccount account) throws Exception {
        Connection conn = currentThreadConnectionManager.getCurrentThreadConn();

        String sql = " UPDATE T_ACCOUNT SET BALANCE_AMOUNT=? WHERE ID=? ";

        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setDouble(1,account.getBalanceAmount());
        preparedStatement.setInt(2,account.getId());
        int result = preparedStatement.executeUpdate();

        return result;
    }
}
